package com.example.a2032.Utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.List;

public class WifiConnectUtils {
    private final WifiManager mWifiManager;
    private final WifiInfo mWifiInfo;
    Context context;
    private ConnectivityManager connManager;

    public WifiConnectUtils(Context context) {
        // 取得WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
        this.context = context;
    }

    // 打开WIFI
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
            Log.i(TAG, "openWifi: ");
        }
    }

    // 关闭WIFI
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    // 检查当前WIFI状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    private static final String TAG = "WifiConnectUtils";

    public void connectWifi(String ssid, String password, int type) {
        openWifi();
        Log.i(TAG, "connectWifi: "+mWifiInfo.getSSID());

        if(isWifiConnect()&&isSameWifi(ssid))return;
        WifiConfiguration wifiConfiguration = createWifiInfo(ssid, password, type);
        Log.i(TAG, "connectWifi: networkId " + wifiConfiguration.networkId);
        if (wifiConfiguration.networkId > 0) {
            mWifiManager.enableNetwork(wifiConfiguration.networkId, true);
            mWifiManager.updateNetwork(wifiConfiguration);
        } else {
            int wcgID = mWifiManager.addNetwork(wifiConfiguration);
            Log.i(TAG, "connectWifi: wcgID " + wcgID);
            mWifiManager.enableNetwork(wcgID, true);

        }
        mWifiManager.saveConfiguration();

    }

    public boolean isSameWifi(String name){
        String connectWifiName=mWifiInfo.getSSID();
        return connectWifiName.replace("\"","").equals(name);

    }

    public WifiConfiguration createWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        WifiConfiguration tempConfig = IsExists(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        if (Type == WifiConfiguration.SECURITY_TYPE_OPEN) //没有密码的情况
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (Type == WifiConfiguration.SECURITY_TYPE_WEP) //WEP加密的情况
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (Type == WifiConfiguration.SECURITY_TYPE_PSK) //WPA加密的情况
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration IsExists(String SSID) {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        if (existingConfigs == null) return null;
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    // 检查wifi是否处开连接状态
    private boolean isWifiConnect() {
        if (connManager == null) {
            connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        return mWifiInfo.isConnected();
    }

    // 检查Wifi连接的是否有网络
    public boolean isOpenNetwork() {
        if (connManager == null) {
            connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
        NetworkInfo mWifiInfo = connManager.getActiveNetworkInfo();
        if (mWifiInfo != null) {
            return mWifiInfo.isAvailable();
        }
        return false;
    }

    // 获得Wifi信号强度
    public int GetWifiSignal() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        //获得信号强度值
        int level = wifiInfo.getRssi();
        int signal=WifiManager.calculateSignalLevel(level,4);
        return signal;
    }

}
